// 将html整页分割多成多页
export function paginateRichHTML(htmlContent, pageHeight = 1000) {
  const tempContainer = document.createElement("div");
  tempContainer.style.width = "800px";
  tempContainer.style.height = pageHeight + "px";
  tempContainer.style.padding = "40px";
  tempContainer.style.boxSizing = "border-box";
  tempContainer.style.position = "absolute";
  tempContainer.style.visibility = "hidden";
  document.body.appendChild(tempContainer);

  const parser = new DOMParser();
  const doc = parser.parseFromString(htmlContent, "text/html");
  const elements = Array.from(doc.body.children);
  console.log("elements: ", elements);

  const pages = [];
  let currentPageElements = [];
  tempContainer.innerHTML = "";

  elements.forEach((el) => {
    tempContainer.appendChild(el.cloneNode(true));

    if (tempContainer.scrollHeight > tempContainer.clientHeight) {
      // 超出，保存当前页内容
      const pageHTML = currentPageElements.map((e) => e.outerHTML).join("");
      pages.push(pageHTML);

      // 重新开始新一页
      currentPageElements = [el.cloneNode(true)];
      tempContainer.innerHTML = "";
      tempContainer.appendChild(el.cloneNode(true));
    } else {
      currentPageElements.push(el.cloneNode(true));
    }
  });

  // 最后一页
  if (currentPageElements.length > 0) {
    const pageHTML = currentPageElements.map((e) => e.outerHTML).join("");
    pages.push(pageHTML);
  }

  document.body.removeChild(tempContainer);

  return pages; // 每一页的 HTML 字符串
}

// 处理每页的html，判断每页如果有图片或者是表格，则不分栏，如果没有则分成2栏，如果分栏则添加class名：multicolumn，如果不分栏则不添加
export function processPageHTML(pagesStrList) {
  return pagesStrList.map((pageHTML) => {
    const parser = new DOMParser();
    const doc = parser.parseFromString(pageHTML, "text/html");
    const images = doc.querySelectorAll("img");
    const tables = doc.querySelectorAll("table");
    const div = document.createElement("div");
    div.classList.add("page-break");

    if (images.length > 0 || tables.length > 0) {
      div.innerHTML = pageHTML;
      return div.outerHTML;
    } else {
      div.innerHTML = pageHTML;
      div.classList.add("multicolumn");
      return div.outerHTML;
    }
  });
}
